import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class NeimengguXamxzgsrlzyhshbzjD38CPolicy(BaseTaxPolicySpider):
    name = "neimenggu_xamxzgsrlzyhshbzj_d38c_policy"

    province: str = "内蒙古自治区"  # 取表格
    city: str = "兴安盟"  # 取表格
    county: str = ""  # 取表格
    park: str = "None"  # 取表格
    source: str = "兴安盟行政公署人力资源和社会保障局"  # 取表格 同一个来源合并
    url: str = "http://rsj.xam.gov.cn/rsj/1151470/1151479/index.html"  # 注明入口网址，以便后续排错

    def start_requests(self):
        urls = [self.url]
        for url in urls:
            yield scrapy.Request(url, callback=self.parse_response)

    def parse_response(self, response, **kwargs):
        url = response.xpath("//a[@title='下一页']/@onclick").re_first("""this,'(.*)'""")
        if not url:
            url = response.url
        print(url)
        yield response.follow(url, callback=self.parse_list, dont_filter=True)

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        for elem in response.xpath(
                "//div[@class='news_con' or @class='fileLibrary' or @opentype='page']//ul/li//a[contains(@href, 'htm') or @title]/ancestor::li[string-length(string(.))>=5]"):
            item = Item()
            item['source_url'] = elem.xpath(""".//a/@href""").re_first(r"""(.*/.*)""")
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem.xpath("""string(.)""").get()
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            if '.htm' not in item['source_url'] and '.shtm' not in item['source_url']:
                continue
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            total_page = int(response.xpath(""".""").re_first(r'totalpage="(\d+)"'))
            if total_page > 5:
                new_url = response.xpath("//a[@title='尾页']/@onclick").re_first("""this,'(.*)'""")
            for page_num in range(1, total_page + 1):
                url = re.sub(r"-(\d+)?\.", r"-{}.".format(page_num), response.url)
                print(url)
                yield response.follow(url, callback=self.parse_list, meta={'item': prev_item, 'is_next': False})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get()
        item['content'] = response.xpath(""".""").get()
        item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl neimenggu_xamxzgsrlzyhshbzj_d38c_policy".split())
